﻿using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace BloodApp.Common
{
    public static class FileService
    {
        /// <summary>
        /// 获取指定目录中的匹配项（文件或目录）     string[] strs = GetFileSystemEntries(dir, null, true, false);//此目录下所有的文件和文件夹名称
        /// </summary>
        /// <param name="dir">要搜索的目录</param>
        /// <param name="regexPattern">项名模式（正则）。null表示忽略模式匹配，返回所有项</param>
        /// <param name="recurse">是否搜索子目录</param>
        /// <param name="throwEx">是否抛异常</param>
        /// <returns></returns>
        public static string[] GetFileSystemEntries(string dir, string regexPattern, bool recurse, bool throwEx)
        {
            List<string> lst = new List<string>();
            try
            {
                foreach (string item in Directory.GetFileSystemEntries(dir))
                {
                    try
                    {
                        if (regexPattern == null || Regex.IsMatch(Path.GetFileName(item), regexPattern, RegexOptions.IgnoreCase | RegexOptions.Multiline))
                        { lst.Add(item); }
                        //递归
                        if (recurse && (File.GetAttributes(item) & FileAttributes.Directory) == FileAttributes.Directory)
                        { lst.AddRange(GetFileSystemEntries(item, regexPattern, recurse, throwEx)); }
                    }
                    catch { if (throwEx) { throw; } }
                }
            }
            catch { if (throwEx) { throw; } }
            return lst.ToArray();
        }

        /// <summary>
        /// 获取指定目录中的匹配文件        string[] strs = GetFiles(dir, null, true, true);//此目录下所有的文件名称
        /// </summary>
        /// <param name="dir">要搜索的目录</param>
        /// <param name="regexPattern">文件名模式（正则）。null表示忽略模式匹配，返回所有文件</param>
        /// <param name="recurse">是否搜索子目录</param>
        /// <param name="throwEx">是否抛异常</param>
        /// <returns></returns>
        public static string[] GetFiles(string dir, string regexPattern, bool recurse, bool throwEx)
        {
            List<string> lst = new List<string>();
            try
            {
                foreach (string item in Directory.GetFileSystemEntries(dir))
                {
                    try
                    {
                        bool isFile = (File.GetAttributes(item) & FileAttributes.Directory) != FileAttributes.Directory;

                        if (isFile && (regexPattern == null || Regex.IsMatch(Path.GetFileName(item), regexPattern, RegexOptions.IgnoreCase | RegexOptions.Multiline)))
                        { lst.Add(item); }

                        //递归
                        if (recurse && !isFile) { lst.AddRange(GetFiles(item, regexPattern, recurse, throwEx)); }
                    }
                    catch { if (throwEx) { throw; } }
                }
            }
            catch { if (throwEx) { throw; } }
            return lst.ToArray();
        }

        /// <summary>
        /// 获取指定目录中的匹配目录    string[] strs = GetDirectories(dir, null, true, true);//此目录下所有的子文件夹名称
        /// </summary>
        /// <param name="dir">要搜索的目录</param>
        /// <param name="regexPattern">目录名模式（正则）。null表示忽略模式匹配，返回所有目录</param>
        /// <param name="recurse">是否搜索子目录</param>
        /// <param name="throwEx">是否抛异常</param>
        /// <returns></returns>
        public static string[] GetDirectories(string dir, string regexPattern, bool recurse, bool throwEx)
        {
            List<string> lst = new List<string>();
            try
            {
                foreach (string item in Directory.GetDirectories(dir))
                {
                    try
                    {
                        if (regexPattern == null || Regex.IsMatch(Path.GetFileName(item), regexPattern, RegexOptions.IgnoreCase | RegexOptions.Multiline))
                        { lst.Add(item); }

                        //递归
                        if (recurse) { lst.AddRange(GetDirectories(item, regexPattern, recurse, throwEx)); }
                    }
                    catch { if (throwEx) { throw; } }
                }
            }
            catch { if (throwEx) { throw; } }
            return lst.ToArray();
        }

        /// <summary>
        /// 从文件中(Excel、Access)读取数据,装载到DataTable对象
        /// </summary>
        /// <param name="pathName">绝对路径+文件名</param>
        /// <param name="tableName">表名</param>
        /// <param name="where">查询条件</param>
        /// <returns>DataTable</returns>
        public static DataTable LoadExcelToDataTable(string pathName, string tableName, string where)
        {
            //格式化传入传输
            pathName = pathName.Trim().ToLower();
            tableName = tableName.Trim().ToLower();
            where = where.Trim().ToLower();
            //读取数据
            DataTable tbContainer = new DataTable();
            string strConn = string.Empty;
            if (string.IsNullOrEmpty(tableName)) { tableName = "Sheet1"; }
            FileInfo file = new FileInfo(pathName);
            if (!file.Exists) { throw new Exception("文件不存在"); }
            string extension = file.Extension.Trim().ToLower();
            switch (extension)
            {
                case ".xls"://Excel2003
                    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=No;IMEX=1;'";
                    tableName += "$";
                    break;
                case ".xlsx"://Excel2007
                    strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathName + ";Extended Properties='Excel 12.0;HDR=No;IMEX=1;'";//{IMEX = 0:写,1:读,2:读/写;} {HDR = Yes，第一行是标题} 
                    tableName += "$";
                    break;
                case ".mdb"://Access2003
                    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName;
                    break;
                case ".accdb"://Access2007
                    strConn = "Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" + pathName;
                    //Provider=Microsoft.Ace.OleDb.12.0;Data Source=文件位置;Jet OLEDB:Database Password=密码;
                    break;
            }
            //链接文件
            OleDbConnection cnnxls = new OleDbConnection(strConn);
            //生成SQL字符串
            string sql = string.Format(" select * from [{0}] ", tableName);
            //判断是否有条件
            if (!string.IsNullOrEmpty(where))
            {
                //判读用户是否添加了 where 字符串
                if (-1 == where.IndexOf("where")) where = " where " + where;
                //添加查询条件
                sql += where;
            }
            //读取文件数据
            OleDbDataAdapter oda = new OleDbDataAdapter(sql, cnnxls);
            DataSet ds = new DataSet();
            //将文件里面有表内容装载到内存表中！
            oda.Fill(tbContainer);
            return tbContainer;
        }
    }
}
